package com.oyjd.business.widget;

import java.text.SimpleDateFormat;
import java.util.Timer;
import java.util.TimerTask;

import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.widget.RemoteViews;

import com.oyjd.R;
import com.oyjd.business.activity.GridViewDemo;
import com.oyjd.framework.log.MyLog;

/**
 * 桌面快捷应用示例
 * 
 * @author 欧建东
 * @email oyjd@163.com
 * 
 */
public class MyAppWidgetProvider extends AppWidgetProvider {
	private static final String TAG = "MyAppWidgetProvider";
	private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	private static Timer timer;
	private static int[] appWidgetIds;

	/**
	 * 更新
	 */
	@Override
	public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
		super.onUpdate(context, appWidgetManager, appWidgetIds);
		MyAppWidgetProvider.appWidgetIds = appWidgetIds;
		int n = appWidgetIds.length;
		String time = sdf.format(System.currentTimeMillis());
		for (int i = 0; i < n; i++) {
			int appWidgetId = appWidgetIds[i];
			RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.appwidget);
			views.setImageViewResource(R.id.aw_img, R.drawable.smoke);
			views.setTextViewText(R.id.aw_tv, time);
			PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, new Intent(context, GridViewDemo.class), PendingIntent.FLAG_UPDATE_CURRENT);
			views.setOnClickPendingIntent(R.id.aw_tv, pendingIntent);
			appWidgetManager.updateAppWidget(appWidgetId, views);
		}
	}

	/**
	 * 当最后一个窗口部件实例被移除时调用
	 */
	@Override
	public void onDisabled(Context context) {
		super.onDisabled(context);
		MyLog.d(TAG, "===========remove all widget");
		if (timer != null) {
			timer.cancel();
		}
	}

	/**
	 * 当第一个窗口部件实例被创建时调用
	 */
	@Override
	public void onEnabled(final Context context) {
		super.onEnabled(context);
		MyLog.d(TAG, "===========add first widget");
		timer = new Timer();
		timer.schedule(new TimerTask() {
			@Override
			public void run() {
				if (appWidgetIds != null) {
					onUpdate(context, AppWidgetManager.getInstance(context), appWidgetIds);
				}
			}
		}, 0, 1000);

	}

}
